<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }

        #myCanvas{
            /* width: 400px;
            height: 300px; */
            border: 2px solid #000;
            margin: 100px auto;
            display: block;
        }

    </style>
</head>
<body>
    <!-- 创建画布区域 -->
    <canvas id="myCanvas" width="400px" height="400px"></canvas>
    <script>
        window.onload = function() {
            canvas = document.getElementById('myCanvas')
            ctx = canvas.getContext('2d')
            document.addEventListener('keydown', keyPush)
            setInterval(draw, 1000/10)
        }
        
        sx = sy = 10
        gs = tc = 20
        xv = yv = 0
        ax = ay = 15
        snake = []
        len = 5
        
        function draw() {
            sx += xv
            sy += yv

            if(sx<0) {
                sx = tc-1
            }
            if(sx>tc-1) {
                sx = 0
            }
            if(sy<0) {
                sy = tc-1
            }
            if(sy>tc-1) {
                sy = 0
            }
            // ctx.rect(canvas.width/2 - sx, canvas.height/2 - sy, sx, sy)

            ctx.fillStyle = "greenyellow"
            ctx.fillRect(0, 0, canvas.width, canvas.height)

            ctx.fillStyle = "#000"
            for(var i=0; i<snake.length; i++) {
                // console.log(snake[i].x, snake[i].x)
                ctx.fillRect(snake[i].x*gs, snake[i].y*gs, gs-2, gs-2)
                if(snake[i].x == sx && snake[i].y == sy) {
                    // console.log(555)
                    len = 5;
                }
            }
            snake.push({x:sx, y:sy})
            while(snake.length > len){
                console.log(snake.length)
                snake.shift()
            }

            if(ax==sx && ay==sy) {
                len++
                ax = Math.floor(Math.random()*tc)
                ay = Math.floor(Math.random()*tc)
            }
            ctx.fillStyle = "red"
            ctx.fillRect(ax*gs, ay*gs, gs-2, gs-2)

        }

        function keyPush(e) {
            switch(e.keyCode) {
                case 37: 
                    xv=-1;yv=0;
                    break;
                case 38:
                    xv=0;yv=-1;
                    break;
                case 39:
                    xv=1;yv=0;
                    break;
                case 40:
                    xv=0;yv=1;
                    break;
            }
                
        }

        
    </script>
    
    
</body>
</html>